import axios from 'axios';
import { message } from 'antd';

console.log('PRODUCTION=====', PRODUCTION);
const instance = axios.create( {
    baseURL: PRODUCTION? '/api' : '/apis',
} );

instance.interceptors.request.use( config => {
    let _token = localStorage.getItem('_token');
    if (_token) {
        let { token, user_id, company_id } = JSON.parse(_token);
        Object.assign(config.headers, {
            Authorization: token,
            uid: user_id,
            cid: company_id,
        })
    }
    config.headers.source = 'web';
    return config;
}, error => {
    return Promise.reject( error );
} );

instance.interceptors.response.use( response => {
    console.log( response );
    if ( response.status === 200) {
        let data = response.data;
        const code = data.code;
        if (code === 0) {
            return data;
        } else if (code === 5091 || code === 5092 || code === 5093 || code === 5094 || code === 5095 || code === 5096) {
            //alert('excption')
            localStorage.removeItem('_token');
            location.href = '/login';
        } else {
            message.error(data.msg);
            return Promise.reject( response );
        }
    } else {
        message.error('网络错误！');
        return Promise.reject( response );
    }
}, error => {
    return Promise.reject( error );
} );

export default instance;